// 解析服务命令
use serde::{Deserialize, Serialize};
use tauri::command;

use crate::error::AppError;
use crate::services::parser::{ParserService, ParseRequest, ParseResponse, ParseOptions};

// 全局解析服务实例
lazy_static::lazy_static! {
    static ref PARSER_SERVICE: ParserService = ParserService::new();
}

/// 解析文件命令
#[command]
pub async fn parse_file(
    file_path: String,
    content: String,
    language: Option<String>,
    options: Option<ParseOptions>,
) -> Result<ParseResponse, AppError> {
    // 确保服务已初始化
    if let Err(_) = PARSER_SERVICE.initialize().await {
        // 如果初始化失败，尝试重新初始化
        PARSER_SERVICE.initialize().await?;
    }

    let request = ParseRequest {
        file_path,
        content,
        language,
        options: options.unwrap_or_default(),
    };

    PARSER_SERVICE.parse_file(request).await
}

/// 批量解析文件命令
#[command]
pub async fn parse_files(
    requests: Vec<ParseFileRequest>,
) -> Result<Vec<ParseResponse>, AppError> {
    // 确保服务已初始化
    if let Err(_) = PARSER_SERVICE.initialize().await {
        PARSER_SERVICE.initialize().await?;
    }

    let parse_requests: Vec<ParseRequest> = requests
        .into_iter()
        .map(|req| ParseRequest {
            file_path: req.file_path,
            content: req.content,
            language: req.language,
            options: req.options.unwrap_or_default(),
        })
        .collect();

    PARSER_SERVICE.parse_files(parse_requests).await
}

/// 获取支持的语言列表
#[command]
pub async fn get_supported_languages() -> Result<Vec<String>, AppError> {
    // 确保服务已初始化
    if let Err(_) = PARSER_SERVICE.initialize().await {
        PARSER_SERVICE.initialize().await?;
    }

    PARSER_SERVICE.get_supported_languages().await
}

/// 解析文件请求（用于批量解析）
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParseFileRequest {
    pub file_path: String,
    pub content: String,
    pub language: Option<String>,
    pub options: Option<ParseOptions>,
}
